/*
 * Copyright 2009 Colin Prinn
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

package net.recursv.motific.at.command;

import net.recursv.motific.at.AtException;
import net.recursv.motific.at.runner.AtScript;
import net.recursv.motific.at.scene.AtScene;
import net.recursv.motific.at.scene.SceneManager;
import net.recursv.motific.at.scene.SceneRequirement;
import net.recursv.motific.utils.StringList;

import java.util.Vector;

/**
 * User: recursv
 * Date: 16/08/2009
 * Time: 2:01:22 PM
 */
public class AssertSceneContainsCommand extends AtCommand {
    public static final String IDENTIFIER = "AssertSceneContains";
    private Vector _requirements = new Vector();

    public String getTitle() {
        return IDENTIFIER;
    }

    protected void run() throws Throwable {
        AtScene scene;
        long start = System.currentTimeMillis();
        do {
            Thread.sleep(100);
            scene = SceneManager.getScene();
        } while (scene.isEmpty() && System.currentTimeMillis() - start < AtScript.TIMEOUT);

        for (int i = 0; i < _requirements.size(); i++) {
            SceneRequirement requirement = (SceneRequirement) _requirements.elementAt(i);
            if (!scene.contains(requirement))
                throw new AtException(getLineNumber() + ": Scene does not contain -> " + requirement.getOriginal());
        }
    }

    public String toString() {
        return IDENTIFIER + "()";
    }

    public void parse(String params) {
        String str = params.indexOf('{') != -1 ? params.substring(params.indexOf('{') + 1, params.lastIndexOf('}')) : params;
        StringList list = new StringList(str, '\n');
        for (int i = 0; i < list.size(); i++)
            readRequirement(list.get(i).trim());
    }

    public void readRequirement(String s) {
        if (s.length() != 0)
            _requirements.addElement(new SceneRequirement(s));
    }

    public int getRequirementsSize() {
        return _requirements.size();
    }

    public SceneRequirement getRequirement(int index) {
        return (SceneRequirement) _requirements.elementAt(index);
    }

}
